package com.swb.mybatis02.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import sun.swing.SwingLazyValue;

import java.io.IOException;
import java.io.InputStream;

/**
 * @title: MyBatisUtils
 * @author: 流沐颖
 * @date:2022/5/31 12:06
 * @description:
 * @version: study
 */
public class MyBatisUtils {
    private static SqlSessionFactory factory;
    private static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();


    // 静态代码块
    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis_config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * @param
     * @return
     * @title: getMapper
     * @author: 流沐颖
     * @date:2022/6/1 20:01
     * @description: 得到接口的实现类对象 用于调用接口中的方法进行操作
     * @version: study
     */
    public static <T> T getMapper(Class<T> clazz) {
        SqlSession session = getSession();
        //传入接口的类对象,让mybatis生成对应接口的实现最终返回出去
        return session.getMapper(clazz);
    }

    /**
     * @author: 流沐颖
     * @return:
     * @time: 2022/5/31 11:14
     * @description: 获取session链接
     */
    public static SqlSession getSession() {
        SqlSession session = THREAD_LOCAL.get();
        if (session == null) {
            session = factory.openSession();
            THREAD_LOCAL.set(session);
        }
        return session;
    }

    /**
     * @author: 流沐颖
     * @return:
     * @time: 2022/5/31 11:16
     * @description: 关闭链接
     */
    public static void close() {
        SqlSession session = getSession();
        session.close();
        THREAD_LOCAL.remove();
    }

    /**
     * @param
     * @return
     * @title: commit
     * @author: 流沐颖
     * @date:2022/6/1 19:57
     * @description: 对事务进行提交
     * @version: study
     */
    public static void commit() {
        SqlSession session = getSession();
        session.commit();
        close();
    }

    /**
     * @param
     * @return
     * @title: rollback
     * @author: 流沐颖
     * @date:2022/6/1 19:57
     * @description: 事务回滚
     * @version: study
     */
    public static void rollback() {
        SqlSession session = getSession();
        session.rollback();
        close();
    }


}
